package com.wcw.example.intercept;

import com.wcw.example.annotation.IPFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @author ChuangWeiwei;
 * @create 2022.10.10  16:27;
 * @Description 判断是否刷单
 */
@Component
public class IInterceptor implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate redisTemplate;

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final Integer COUNT_LIMIT = 3; // 请求次数限制

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            IPFilter ipFilter = handlerMethod.getMethodAnnotation(IPFilter.class);

            // 标识@IPFilter注解的方法，进行IP过滤
            if (ipFilter != null) {
                String ip = request.getRemoteHost();
                String time = LocalDateTime.now().format(FORMATTER);
                String key = ip + ":" + time;

                // 1、过滤黑名单中的IP
                if (redisTemplate.opsForSet().isMember("ipBlackList", ip)) {
                    failedReturn(response);
                    return false;
                }

                Long count = redisTemplate.opsForValue().increment(key);
                redisTemplate.expire(key, 7, TimeUnit.DAYS);
                // 2、请求次数超过限制则加入黑名单
                if (count >= COUNT_LIMIT) {
                    redisTemplate.opsForSet().add("ipBlackList", ip);
                    failedReturn(response);
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * 写入响应信息
     * @param resp
     */
    private void failedReturn(HttpServletResponse resp) {
        resp.setContentType("application/json;charset=utf-8");
        try (PrintWriter writer = resp.getWriter();){
            writer.print("IP请求次数过多，请稍后重试");
            resp.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
